<?php

/**
 * @copyright 2011
 * @version $Id$
 * @access public
 * @author oriotiori

 */

class Admin_Model_Paypal extends Zend_Db_Table_Abstract{

	protected $_name = 'paypal';


	/**
	 * @param int $id
	 * @return array $data
	 */
	function PPHttpPost($methodName_, $nvpStr_, $To) {



		$environment = 'sandbox';
		$API_UserName = urlencode($To['User']);
		$API_Password = urlencode($To['Pwd']);
		$API_Signature = urlencode($To['Signature']);

		// Set up your API credentials, PayPal end point, and API version.
		$API_Endpoint = "https://api-3t.paypal.com/nvp";
		if("sandbox" === $environment || "beta-sandbox" === $environment) {
			$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
		}
		$version = urlencode('51.0');

		// Set the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);

		// Turn off the server and peer verification (TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);

		// Set the API operation, version, and API signature in the request.
		$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

		// Set the request as a POST FIELD for curl.
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

		// Get response from the server.
		$httpResponse = curl_exec($ch);

		if(!$httpResponse) {
			exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
		}

		// Extract the response details.
		$httpResponseAr = explode("&", $httpResponse);

		$httpParsedResponseAr = array();
		foreach ($httpResponseAr as $i => $value) {
			$tmpAr = explode("=", $value);
			if(sizeof($tmpAr) > 1) {
				$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
			}
		}

		if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
			exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
		}

		return $httpParsedResponseAr;
	}


	public function TestConfigPaypalAccount($to){
		
// 		$transactionID = urlencode('example_transaction_id');
// 		$amount = urlencode('example_amount');
// 		$currency = urlencode('USD');							// or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
// 		$trxType = urlencode('V');
		
// 		// Add request-specific fields to the request string.
// 		$nvpStr="&TRANSACTIONID=$transactionID&AMT=$amount&CURRENCYCODE=$currency&TRXTYPE=$trxType";

// 		$httpParsedResponseAr = $this->PPHttpPost('CreateRecurringPaymentsProfile', $nvpStr, $to);

// 		if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
// 			exit('CreateRecurringPaymentsProfile Completed Successfully: '.print_r($httpParsedResponseAr, true));
// 		} else  {
// 			exit('CreateRecurringPaymentsProfile failed: ' . print_r($httpParsedResponseAr, true));


// 		}

		
		if (isset($_REQUEST['submit']))
		{
			// Live URL: https://api-3t.paypal.com/nvp
			// Test URL: https://api-3t.sandbox.paypal.com/nvp
			$url = 'https://api-3t.paypal.com/nvp';
		
			$amount = 10.00; // Obviously, we would sum up the contents of some cart to fill in this value.
			$credit_card_type = 'VISA';//$_REQUEST['credit_card_type'];
			$credit_card_number = '000'; //$_REQUEST['credit_card_number'];
			$expiration_month = //$_REQUEST['expiration_month'];
			$expiration_year = $_REQUEST['expiration_year'];
			$cvv2 = $_REQUEST['cvv2'];
		
			$first_name = $_REQUEST['first_name'];
			$last_name = $_REQUEST['last_name'];
			$address1 = $_REQUEST['address1'];
			$address2 = $_REQUEST['address2'];
			$city = $_REQUEST['city'];
			$state = $_REQUEST['state'];
			$zip = $_REQUEST['zip'];
		
			$country = 'US'; // Assuming we are only accepting transactions within the United States.
			$currency_code = 'USD'; // Assuming we are using the United States Dollar
			$ip_address = $_SERVER['REMOTE_ADDR']; // Get the IP Address, assuming we are in a LAMP environment
		
			// Create an instance of our PayPal NVP client
			$client = new Admin_Model_Paypalclient($url);
		
			// Send our API request!
			$result = $client->doDirectPayment(
			$amount,
			$credit_card_type,
			$credit_card_number,
			$expiration_month,
			$expiration_year,
			$cvv2,
			$first_name,
			$last_name,
			$address1,
			$address2,
			$city,
			$state,
			$zip,
			$country,
			$currency_code,
			$ip_address);
		
			// Remember to store the transaction ID! You'll need it
			// to lookup the transaction details. For now, let's just
			// display the results.
			echo $result->getBody();
		}
			
			echo '
		<form>
		      <ul>
		            <li><label>First Name:</label><input type="" name="first_name" value="" /></li>
		            <li><label>Last Name:</label><input type="" name="last_name" value="" /></li>
		            <li><label>Address, Line 1:</label><input type="" name="address1" value="" /></li>
		            <li><label>Address, Line 2:</label><input type="" name="address2" value="" /></li>
		            <li><label>City:</label><input type="" name="city" value="" /></li>
		            <li><label>State (2-Letter):</label><input type="state" name="" value="" /></li>
		            <li><label>Zip:</label><input type="" name="" value="zip" /></li>
		      </ul>
		      <ul>
		            <li><label>Card Type</label><input type="VISA" name="" value="" /></li>
		            <li><label></label><input type="" name="" value="" /></li>
		      </ul>
		</form>';
		
		
	}



	/**
	 * @param int $id
	 * @return array $data
	 */
	public function getPaypalAccount($id=0)
	{
		$TO = new Admin_Model_TO_Paypal();
		$data=array();
		try{
			$sql=$this->getAdapter()->select()->from(array('t' => TABLE_PREFIX.$this->_name),array('t.*'))->where("1");

			$res = $this->getAdapter()->fetchAll($sql);
			$rowCount=count($res);

			if($rowCount>0){
				foreach($res as $dt){
					$TO->setId($dt['Id']);
					$TO->setUser($dt['User']);
					$TO->setPwd($dt['Pwd']);
					$TO->setSignature($dt['Signature']);
					$TO->setPaypalLogin($dt['Paypal_Login']);
					$TO->setEmailPaypal($dt['Email_Paypal']);
					$TO->setCurrencyCode($dt['Currency_Code']);
					
					$TO->setSuccessReturn($dt['Success_Return']);
					$TO->setCancelReturn($dt['Cancel_Return']);
					$TO->setNotifyIPNUrl($dt['Notify_IPN_Url']);
					
				}
				$data = $TO->getAllVars();
				
				return $data;
			}
		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}



	/**
	 * @param Array $to
	 * @return boolean
	 */
	public function updatePaypalAccount($to)
	{
		

		try{
			$data = array(
    			'User'  	=> (!empty($to['User'])) ? $to['User'] : new Zend_Db_Expr('null'),
    			'Signature' => (!empty($to['Signature'])) ? $to['Signature'] : new Zend_Db_Expr('null'),
    			'Pwd'  		=> (!empty($to['Pwd'])) ? $to['Pwd'] : new Zend_Db_Expr('null'),
    			'Paypal_Login'  		=> (!empty($to['PaypalLogin'])) ? $to['PaypalLogin'] : new Zend_Db_Expr('null'),
    			'Email_Paypal'  		=> (!empty($to['EmailPaypal'])) ? $to['EmailPaypal'] : new Zend_Db_Expr('null'),
    			'Currency_Code'  		=> (!empty($to['CurrencyCode'])) ? $to['CurrencyCode'] : new Zend_Db_Expr('null'),
    			'Success_Return'  		=> (!empty($to['SuccessReturn'])) ? $to['SuccessReturn'] : new Zend_Db_Expr('null'),
    			'Cancel_Return'  		=> (!empty($to['CancelReturn'])) ? $to['CancelReturn'] : new Zend_Db_Expr('null'),
				'Notify_IPN_Url'  		=> (!empty($to['NotifyIPNUrl'])) ? $to['NotifyIPNUrl'] : new Zend_Db_Expr('null')
			);
			$where[]="1";

			$res = $this->getAdapter()->update(TABLE_PREFIX.$this->_name ,$data, $where);
			return true;

		}catch(Exception $e)
		{
			$error=array($e->getFile(), 'Exception: '.$e->getMessage());
			$ExceptionHandler= new Default_Model_ExceptionHandler();
			$ExceptionHandler->saveErrors($error);
		}
		return false;
	}



}
